/**
 * @project mybatisDemo_zkingbbsxiugai
 * @Title LuceneController.java
 * @description 
 * @Package org.qiuqiu.controller
 * @author wangsongmao  email:wangsongmao@zkingsoft.com
 * @date  2015年5月10日 下午5:44:32
 * 
 */
package org.qiuqiu.controller;

import java.io.StringReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;
import org.qiuqiu.service.impl.PostServiceImpl;
import org.qiuqiu.vo.PaginationVO;
import org.qiuqiu.vo.Post;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.wltea.analyzer.lucene.IKAnalyzer;

/**@project mybatisDemo_zkingbbsxiugai
 * @Title LuceneController.java
 * @Package org.qiuqiu.controller
 * @author wangsongmao  email:wangsongmao@zkingsoft.com
 * @date  2015年5月10日 下午5:44:32
 */
@Controller
public class LuceneController {
	@Autowired(required = false)
	/*IndexWriter indexWriter;*/
	IndexWriterConfig indexWriterConfig;
	@Autowired(required = false)
	IKAnalyzer analyzer;
	@Autowired(required = false)
	SimpleFSDirectory directory;
	@Autowired
	private PostServiceImpl postServiceImpl;
	private Logger log = Logger.getLogger(this.getClass());
	private static final String STARTTAG = "<font color='red'>";
	private static final String ENDTAG = "</font>";
    private IndexWriter indexWriter=null;
    private DateFormat fmt=new SimpleDateFormat("yyyy-MM-dd HH:mm");
	@RequestMapping(value = "/search", method = {RequestMethod.POST,RequestMethod.GET})
	public String showList(@RequestParam(value="test",required=false) String test, Model model,PaginationVO page)
			throws Exception {
		
		if (test != null && !"".equals(test)) {
			if (indexWriter==null) {
				if (IndexWriter.isLocked(directory)) {
					IndexWriter.unlock(directory);
					}
				indexWriter=new IndexWriter(directory, indexWriterConfig);
			}
			/*
			 * log.info("查询数据"); List<Person> personList=null;
			 */	
			this.ntes(page);
			IndexSearcher searcher = new IndexSearcher(
					IndexReader.open(indexWriter.getDirectory()));
			/*int size = indexWriter.maxDoc();*/
			//针对多个field进行解析查询在name中查找
			QueryParser parser = new MultiFieldQueryParser(Version.LUCENE_48,
					new String[] { "title","content" }, analyzer);
		
			Query query = parser.parse(test);
			
            //执行查询，满足前400条的结果 3280135924
			TopDocs td = searcher.search(query, page.getPageSize(),new Sort(new SortField("newsId", SortField.Type.STRING, false)));
            System.out.println("满足条件的数"+td.totalHits);
            page.setTotalField(td.totalHits);
            //获得每个结果
			ScoreDoc[] sd = td.scoreDocs;
            //高亮显示
			SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter(
					STARTTAG, ENDTAG);

			Highlighter highlighter = new Highlighter(simpleHtmlFormatter,
					new QueryScorer(query));

			Document doc;

			TokenStream tokenStream = null;

			Post p = null;
			List<Post> list = new ArrayList<Post>();

			String name;
            String content;
			for (int i = 0; i < sd.length; i++) {
				p = new Post();

				int docId = sd[i].doc;
				doc = searcher.doc(docId);

				name = doc.get("title");
				//
				tokenStream = analyzer.tokenStream("title", new StringReader(
						name));
				name = highlighter.getBestFragment(tokenStream, name);
				p.setPostTitle(name == null ? doc.get("title") : name);

				
				  content=doc.get("content");
				 tokenStream=analyzer.tokenStream("content", new
				  StringReader(content));
				 content=highlighter.getBestFragment(tokenStream, content);
				

				// 正文部分，如果没有匹配的关键字，截取前200个字符
				
				  p.setPostContent(content==null?(doc.get("content").length()<200
				  ?doc.get("content"):doc.get("content").substring(0,
				  199)):content);
				
				
				p.setPostid(Integer.parseInt(doc.get("postid")));
				p.setPostUsername(doc.get("username"));
				p.setPostCreatetime(fmt.parse(doc.get("createtime")));
			/*	p.setPersonid(Integer.parseInt(doc.get("age")));*/
				list.add(p);
				

			}
			model.addAttribute("postArrayList", list);
			model.addAttribute("page", page);
		}
		/*indexWriter.close();*/
		return "Lucene";

	}

	public void ntes(PaginationVO page) throws Exception {

		List<Post> list =postServiceImpl.findallClickandInfo(page);
        log.info(list);
		// 重复抓取会重复添加索引
		indexWriter.deleteAll();
        indexWriter.commit();
		Document doc = null;
		for (Post p : list) {
			doc = new Document();
			Field title = new Field("title", p.getPostTitle(), Field.Store.YES,
					Field.Index.ANALYZED);//Store.YES 存储  Index.ANALYZED 分词建立索引 保存权重信息
			
			Field content = new Field("content",
			  p.getPostContent(),Field.Store.YES, Field.Index.ANALYZED);
			
			Field postid = new Field("postid", p.getPostid().toString(),
					Field.Store.YES, Field.Index.NO);
			Field username = new Field("username", p.getPostUsername(),
					Field.Store.YES, Field.Index.NO);
			Field createtime = new Field("createtime", fmt.format(p.getPostCreatetime()),
					Field.Store.YES, Field.Index.NO);
			
			doc.add(title);
			doc.add(content);
			doc.add(postid);
			doc.add(username);
			doc.add(createtime);
			indexWriter.addDocument(doc);
		}
		indexWriter.commit();
	}
}
